import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

public class test_DriverManager {
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/mysql_practice?characterEncoding=utf8&allowPublicKeyRetrieval=true&useSSL=false";
    private static final String USER = "root";
    private static final String PASSWORD = "Langwang0823*";
    public static void main(String[] args){
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try{
            // 加载数据库厂商提供的驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 获取数据库连接
            connection = DriverManager.getConnection(URL, USER, PASSWORD);
            // 创建Statement对象
            statement = connection.createStatement();
            // 定义并执行SQL语句
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入要查询的学生姓名：");
            String name = scanner.next();
            // 不安全，出现sql注入
            //String name = "' or '1'='1";
            String sql = "select student_id, sn, name, mail, class_id from student where name = '" + name + "'";
            // 执行sql语句，获取查询结果
            resultSet = statement.executeQuery(sql);
            // 遍历结果集，获取数据
            while(resultSet.next()){
                long stuId = resultSet.getLong(1);
                String stuSn = resultSet.getString(2);
                String stuName = resultSet.getString(3);
                String stuMail = resultSet.getString(4);
                long classId = resultSet.getLong(5);
                System.out.println(MessageFormat.format("学生编号={0}, 学号={1}, 学生姓名={2}, 邮箱={3}, 班级编号={4}", stuId, stuSn,
                        stuName, stuMail, classId));
            }
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }catch (SQLException e){
            e.printStackTrace();
        } finally{
            //依次释放资源，关闭连接
            if(resultSet != null){
                try{
                    resultSet.close();
                }catch(SQLException e){
                    e.printStackTrace();
                }
            }
            if(statement != null){
                try{
                    statement.close();
                }catch(SQLException e){
                    e.printStackTrace();
                }
            }
            if(connection != null){
                try{
                    connection.close();
                }catch(SQLException e){
                    e.printStackTrace();
                }
            }
        }
    }
}
